package com.softeem.xyblogmaster.jwt;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import javax.crypto.SecretKey;
import java.util.Date;

@Component
public class JwtUtil {

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private long expiration;

    // 生成JWT令牌
    public String generateToken(int uid) {
        // 将密钥转换为 SecretKey 对象
        SecretKey key = Keys.hmacShaKeyFor(secret.getBytes());

        return Jwts.builder()
                .subject(String.valueOf(uid)) // 设置主题
                .issuedAt(new Date()) // 签发时间
                .expiration(new Date(System.currentTimeMillis() + expiration)) // 过期时间
                .signWith(key) // 使用密钥签名
                .compact();
    }


    //校验token是否是签发的
    public  void  verify(String token){
        SecretKey secretKey = Keys.hmacShaKeyFor(secret.getBytes());
        Jws<Claims> claimsJws = Jwts.parser()
                .verifyWith(secretKey) // <----
                .build()
                .parseSignedClaims(token);
    }


    //校验token是否已经过期了
    public boolean isTokenExpired(String token) {
        SecretKey secretKey = Keys.hmacShaKeyFor(secret.getBytes());
        Jws<Claims> claimsJws = Jwts.parser()

                .verifyWith(secretKey) // <----
                .build()
                .parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return claims.getExpiration().after(new Date());
    }

    //getuid
    public Long getUid(String token) {
        SecretKey secretKey = Keys.hmacShaKeyFor(secret.getBytes());
        Jws<Claims> claimsJws = Jwts.parser()
                .verifyWith(secretKey) // <----
                .build()
                .parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return Long.parseLong(claims.getSubject());
    }



}